﻿using UnityEngine;
using System.Collections;

/// <summary>
/// Reusable Singleton Class for Unity Gameobject.
/// </summary>
/// <typeparam name="T">class to use singleton</typeparam>
public static class wsSingletonObject<T>
        where T : MonoBehaviour
{
    static volatile T _instance;
    static object _lock = new object();

    /// <summary>
    /// name of new gameobject.
    /// </summary>
    static public string name = "wsSingletonObject";
    /// <summary>
    /// parent name of new gameobject.
    /// </summary>
    static public string parentName = "";

    static wsSingletonObject()
    {
    }

    /// <summary>
    /// Get Instance.
    /// </summary>
    public static T Instance
    {
        get
        {
            _instance = UnityEngine.GameObject.FindObjectOfType(typeof(T)) as T;

            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new UnityEngine.GameObject(name, typeof(T)).GetComponent<T>();

                        if (parentName.Length > 0 && _instance.transform.parent == null)
                        {
                            GameObject parent = GameObject.Find(parentName);
                            _instance.transform.parent = parent.transform;
                        }
                    }
                }
            }

            return _instance;
        }
    }

	/// <summary>
	/// dont destoy object but aleady object exist then destroy alter object.
	/// </summary>
	/// <param name="gameObject"></param>
	public static void Awake(UnityEngine.GameObject gameObject)
	{
		if (wsSingletonObject<T>.Instance != null)
		{
			if (wsSingletonObject<T>.Instance.gameObject != gameObject)
			{
				UnityEngine.MonoBehaviour.Destroy(gameObject);
			}
		}
		else
		{
			UnityEngine.MonoBehaviour.DontDestroyOnLoad(gameObject);
		}
	}
}